package com.service.impl;

import com.service.DocService;
import com.utils.ConnectionUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.util.Map;


public class DocServiceImpl implements DocService {


    @Override
    public void addDoc(String index, Map source) throws Exception {
        RestHighLevelClient client = ConnectionUtils.getClient();
        IndexResponse response = client.index(new IndexRequest(index).source(source), RequestOptions.DEFAULT);
        System.err.println(response.toString());

    }

    @Override
    public void addDoc(String index, String jsonSource) throws Exception {
        RestHighLevelClient client = ConnectionUtils.getClient();
        IndexResponse response = client.index(new IndexRequest(index).source(jsonSource, XContentType.JSON), RequestOptions.DEFAULT);
        System.err.println(response.toString());
    }

    @Override
    public void addDocWithId(String index, String jsonSource, String id) throws Exception {
        RestHighLevelClient client = ConnectionUtils.getClient();
        IndexResponse response = client.index(new IndexRequest(index).source(jsonSource, XContentType.JSON).id(id), RequestOptions.DEFAULT);
        System.err.println(response.toString());
    }

    @Override
    public void getDocById(String index, String id) throws Exception {
        RestHighLevelClient client = ConnectionUtils.getClient();
        GetResponse response = client.get(new GetRequest(index, id), RequestOptions.DEFAULT);
        System.err.println(response.getSourceAsString());
    }

    @Override
    public void updateDocById(String index, String id, String jsonSource) throws Exception {
        RestHighLevelClient client = ConnectionUtils.getClient();
        UpdateResponse response = client.update(new UpdateRequest(index, id).doc(jsonSource, XContentType.JSON), RequestOptions.DEFAULT);
        System.err.println(response.toString());
    }

    @Override
    public void deleteDocById(String index, String id) throws Exception {
        RestHighLevelClient client = ConnectionUtils.getClient();
        DeleteResponse response = client.delete(new DeleteRequest(index, id), RequestOptions.DEFAULT);
        System.err.println(response.toString());
    }
}
